package com.caoheng.pay.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.caoheng.core.common.Result;
import com.caoheng.core.common.body.PayRequestBody;
import com.caoheng.entity.PayChannel;
import com.caoheng.entity.PayChannelExample;
import com.caoheng.mapper.PayChannelMapper;
import com.caoheng.pay.pay.PayExecutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.caoheng.core.util.ResultUtil.error;
import static org.springframework.util.CollectionUtils.isEmpty;

/**
 * @ClassName com.caoheng.pay.service.ThirdPayService
 * @Description 第三方支付相关服务处理
 * @Author shuimodanqing
 * @Date 2018/12/24 9:04 AM
 */
@Service
public class ThirdPayService {

    @Autowired
    private PayChannelMapper payChannelMapper;

    @Autowired
    private PayExecutor payExecutor;


    public Result payOrder(PayRequestBody body) {
        if (body.getMerchantId() == null || body.getPayType() == null) {
            return error("参数错误: MerchantId is " + body.getMerchantId() + ", payType is " + body.getPayType());
        }

        PayChannelExample payChannelExample = new PayChannelExample();
        PayChannelExample.Criteria criteria = payChannelExample.createCriteria();
        criteria.andMerchantChannelIdEqualTo(body.getMerchantId()).andPayTypeEqualTo(body.getPayType());
        List<PayChannel> payChannelList = payChannelMapper.selectByExample(payChannelExample);
        if (isEmpty(payChannelList)) {
            return error("暂无此商户渠道: param[ merchantId: " + body.getMerchantId() + ",payType: " + body.getPayType() + "]");
        }
        PayChannel payChannelToUse = payChannelList.get(0);
        //1.获取当前渠道对应的参数(json)
        String channelParamToUse = payChannelToUse.getParam();
        //2.将对应的支付渠道参数，转换成json对象
        JSONObject channelParamObj = JSON.parseObject(channelParamToUse);
        //3.调用支付执行器执行支付逻辑处理(参数的验签、支付结果的返回处理)
        payExecutor.execute(channelParamObj,body);

        return null;
    }

}
